package com.fucheng.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.Collections;
import java.util.List;

/**
 * 使用 Zookeeper 实现的服务注册
 */
public class ZookeeperServiceRegistry implements ServiceRegistry {

    // 服务的根结点
    private static final String ROOT_PATH = "/rpc";

    private final CuratorFramework client;

    /**
     * 构造方法中启动 Curator 客户端，并设置命名空间为 /registry
     */
    public ZookeeperServiceRegistry() {
        this.client = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181") // Zookeeper 连接地址
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
                .namespace("registry")
                .build();
        client.start();
    }

    /**
     * 向 Zookeeper 注册服务，将服务地址写入指定路径
     */
    public void register(String serviceName, String address) {
        try {
            // 所有服务会被写入路径 /registry/rpc/{serviceName}/{address}
            String servicePath = ROOT_PATH + "/" + serviceName + "/" + address;

            if(client.checkExists().forPath(servicePath) == null){
                // 创建临时节点（服务断开时自动清除）
                client.create()
                        .creatingParentsIfNeeded()
                        .withMode(CreateMode.EPHEMERAL)
                        .forPath(servicePath);
                System.out.println("[ZK] 已注册服务：" + serviceName);
            }
        } catch (Exception e) {
            throw new RuntimeException("注册服务失败：" + serviceName, e);
        }
    }

}
